package main

import (
	"flag"
	log "github.com/golang/glog"
	"github.com/grpc-ecosystem/grpc-gateway/runtime"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	pb "grpc-test/pb"
	"net"
	"net/http"
)

const (
	port = ":50051"
)

func httpServer(rpcPort, httpPort string) {
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	mux := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithInsecure()}
	err := pb.RegisterGreeterHandlerFromEndpoint(ctx, mux, rpcPort, opts)
	if err != nil {
		log.Error(err)
	}
	http.ListenAndServe(httpPort, mux)
}

func main() {
	rpcPort := flag.String("rpcPort", ":9010", "")
	httpPort := flag.String("httpPort", ":9011", "")
	flag.Parse()
	defer log.Flush()
	log.Info("start", *rpcPort, *httpPort)
	go httpServer(*rpcPort, *httpPort)

	lis, err := net.Listen("tcp", *rpcPort)
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{})
	s.Serve(lis)
}
